package cu.tedu._05mvcboot02.exception;

import cu.tedu._05mvcboot02.common.response.JsonResult;
import cu.tedu._05mvcboot02.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult IllegalArgumentException(IllegalArgumentException exception) {
        String message = exception.getMessage();
        log.error("IllegalArgumentException:" + message);
        return new JsonResult(StatusCode.OPERATION_FAILED, message);
    }
    @ExceptionHandler
    public  JsonResult BindException(BindException exception){
        String message= exception.getFieldError().getDefaultMessage();
        log.error("BindException:"+message);
        return new JsonResult(StatusCode.OPERATION_FAILED,message);
    }

    @ExceptionHandler
    public JsonResult ConstraintViolationException(ConstraintViolationException exception ){
        String message= exception.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:"+message);
        return new JsonResult(StatusCode.OPERATION_FAILED,message);
    }

//    @ExceptionHandler
//    public JsonResult RuntimeException(RuntimeException exception) {
//        log.error("RuntimeException:" + exception.getMessage());
//        return new JsonResult(StatusCode.OPERATION_FAILED, exception.getMessage());
//    }

//    @ExceptionHandler
//    public JsonResult Throwable(Throwable throwable) {
//        log.error("Throwable:" + throwable.getMessage());
//        return new JsonResult(StatusCode.OPERATION_FAILED,throwable.getMessage());
//    }
}
